package com.ews.onlineexchange.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.ConversationScoped;
import javax.enterprise.event.Event;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import com.ews.onlineexchange.model.*;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import com.ews.onlineexchange.model.bulletinRequirement.Requirement;
import com.ews.onlineexchange.service.DeterminedRecordService;
import com.ews.onlineexchange.service.EntityHome;
import com.ews.onlineexchange.service.MessgaePushService;
import com.ews.onlineexchange.service.SmsService;
import com.ews.onlineexchange.service.UserService;
import com.ews.onlineexchange.service.qualifier.MessagePushWsEvent;
import com.ews.onlineexchange.util.AttachmentUtils;

@Named
@ConversationScoped
public class TradeController extends EntityHome<Trade, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	@Inject
	SmsService smsService;
	@Inject
	DeterminedRecordService recordService;
	@Inject
	UserService userService;
	
	@Inject
	@MessagePushWsEvent
	Event<String> messagePushWsEvent;
	@Inject
	MessgaePushService messgaePushService;
	@Override
	public String saveAndFlush() {
		if (!validateRequirements()) {
			return null;
		}
		if(recordService.isExistSupplierInRecord(userService.getLoginedUser().getId())) {
			FacesContext.getCurrentInstance().addMessage("",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "非常抱歉，由于您在近期出勤率检查考核中未达到要求，暂时无法报名，请按照要求进行整改！", ""));
			return null;
		}
		Bulletin bulletin = getInstance().getBulletin();
		if (bulletin.getEndingApplyTime().getTime() < new Date().getTime()) {
			FacesContext.getCurrentInstance().addMessage("",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "截止申请时间不能早于当前时间！", ""));
			return null;
		}
		
//		bulletin.setHasAppliedCount(bulletin.getAppliedCount() + 1);
		getEntityManager().merge(bulletin);
		generateRequirements();
		getInstance().setApply(true);
		getInstance().setApplyTime(new Date());
		getInstance().setHasVerify(true);
		getInstance().setVerifyTime(new Date());
		getInstance().setCancelAudit("0");
		String result = super.saveAndFlush();
		//短信邀请
		if(result.equals(RESULT_SAVED)) {
			smsService.addSuccessAppliedMessageToSupplier(getInstance());
			//中介报名成功消息推送
			String pushMessage = messgaePushService.addSuccessAppliedMessageToSupplier(getInstance());
			messagePushWsEvent.fire(pushMessage);
			String msg = "报名成功!";
			if(bulletin.getWayOfChoose().equals(ChooseType.Average) || bulletin.getWayOfChoose().equals(ChooseType.Price)){
				msg += "请于选取时间截止前登录系统按照操作提示进行报价。";
			}
			FacesMessage message = new FacesMessage(msg);
	        FacesContext.getCurrentInstance().addMessage(null, message);
	        //使用ajax请求 不进行跳转
//			return result;
		}
		return null;
	}
	private Map<Integer, List<Attachment>> uploadMap = new HashMap<>();
	
	public void uploadAttachment(FileUploadEvent event) {
		String clientId = event.getComponent().getClientId();
		Integer index = Integer.parseInt(getIteratorClientIndex(clientId));
		
		List<Attachment> attrList = getUploadMap().get(index);
		if (attrList == null) attrList = new ArrayList<Attachment>();
		Attachment attr = getAttachment(event.getFile());
		attrList.add(attr);
		getUploadMap().put(index, attrList);
		FacesMessage message = new FacesMessage(event.getFile().getFileName() + " 上传成功。");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public void removeAttachment( Integer index,Attachment attachment ) {
		getUploadMap().get(index).remove( attachment );
		System.out.println(getUploadMap());
	}
	@Inject
	AttachmentUtils attachmentUtils;
	
	private Attachment getAttachment(UploadedFile file) {
		Attachment attr = attachmentUtils.getAttachmentFromUpload(file);
		return attr;
	}
	private static String getIteratorClientIndex(String clientId) {
		clientId = clientId.substring(0, clientId.lastIndexOf(":"));
		clientId = clientId.substring(clientId.lastIndexOf(":") + 1, clientId.length());
		return clientId;
	}
//
	private void generateRequirements() {		
		Integer i = 0;
		for (Iterator<RequirementDefination> iterator = getInstance().getBulletin().getDefs().iterator(); iterator.hasNext();) {
			RequirementDefination def = (RequirementDefination) iterator.next();
			Requirement requiremnt = new Requirement();
			requiremnt.setAttachments(getUploadMap().get(i));
			requiremnt.setRequirementDefination(def);
			getInstance().getRequirements().add(requiremnt);
			i++;
		}
	}
	
	private boolean validateRequirements() {
		Integer i = 0;
		boolean hasError = false;
		for (Iterator<RequirementDefination> iterator = getInstance().getBulletin().getDefs().iterator(); iterator.hasNext();) {
			RequirementDefination _def = (RequirementDefination) iterator.next();
			List<Attachment> uploadedFiles = uploadMap.get(i);
			if (_def.isRequired() && (uploadedFiles == null || uploadedFiles.isEmpty())) {
				FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "报名未成功！"+_def.getRequiredName() + "必须上传。","");
		        FacesContext.getCurrentInstance().addMessage(null, message);
		        hasError = true;
			}
			i++;
		}
		if (hasError)
			return false;
		return true;
	}

	public Map<Integer, List<Attachment>> getUploadMap() {
		return uploadMap;
	}

	public void setUploadMap(Map<Integer, List<Attachment>> uploadMap) {
		this.uploadMap = uploadMap;
	}

	public void uploadSocialSecurityDatas( FileUploadEvent event ) {		
		if ( event.getFile() == null ) {
			return;
		}

		Attachment attr = attachmentUtils.getAttachmentFromUpload( event.getFile() );
		getInstance().getTradeReportData().getSocialSecurityDatas().add( attr );
		FacesMessage message = new FacesMessage( event.getFile().getFileName() + " 上传成功。" );
		FacesContext.getCurrentInstance().addMessage( null, message );		
	}
	
	public void removeSocialSecurityData( Attachment attachment ) {
		this.getInstance().getTradeReportData().getSocialSecurityDatas().remove(attachment);
	}

	public void uploadEffectDatas( FileUploadEvent event ) {		
		if ( event.getFile() == null ) {
			return;
		}

		Attachment attr = attachmentUtils.getAttachmentFromUpload( event.getFile() );
		getInstance().getTradeReportData().getEffectDatas().add( attr );
		FacesMessage message = new FacesMessage( event.getFile().getFileName() + " 上传成功。" );
		FacesContext.getCurrentInstance().addMessage( null, message );		
	}
	
	public void removeEffectData( Attachment attachment ) {
		this.getInstance().getTradeReportData().getEffectDatas().remove(attachment);
	}

	public void uploadPersonnelCertDatas( FileUploadEvent event ) {		
		if ( event.getFile() == null ) {
			return;
		}

		Attachment attr = attachmentUtils.getAttachmentFromUpload( event.getFile() );
		getInstance().getTradeReportData().getPersonnelCertDatas().add( attr );
		FacesMessage message = new FacesMessage( event.getFile().getFileName() + " 上传成功。" );
		FacesContext.getCurrentInstance().addMessage( null, message );		
	}
	
	public void removePersonnelCertData( Attachment attachment ) {
		this.getInstance().getTradeReportData().getPersonnelCertDatas().remove(attachment);
	}

	public void uploadOtherDatas( FileUploadEvent event ) {		
		if ( event.getFile() == null ) {
			return;
		}

		Attachment attr = attachmentUtils.getAttachmentFromUpload( event.getFile() );
		getInstance().getTradeReportData().getOtherDatas().add( attr );
		FacesMessage message = new FacesMessage( event.getFile().getFileName() + " 上传成功。" );
		FacesContext.getCurrentInstance().addMessage( null, message );		
	}
	
	public void removeOtherData( Attachment attachment ) {
		this.getInstance().getTradeReportData().getOtherDatas().remove(attachment);
	}
	

	
	
	
}
